package cn.iocoder.yudao.module.famous.doctor.controller.app.performance;

import cn.hutool.core.util.IdUtil;

import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.module.famous.doctor.controller.app.operator.utils.Query;
import cn.iocoder.yudao.module.famous.doctor.controller.app.operator.vo.OperatorPerformanceHead;
import cn.iocoder.yudao.module.famous.doctor.controller.app.performance.vo.PerformancePublish;
import cn.iocoder.yudao.module.famous.doctor.controller.app.performance.vo.PerformanceHead;
import cn.iocoder.yudao.module.famous.doctor.controller.app.performance.vo.PerformancePublishItem;
import cn.iocoder.yudao.module.famous.doctor.dal.dataobject.form.UserProjectItemEntity;
import cn.iocoder.yudao.module.famous.doctor.dal.mysql.operator.OperatorPerformanceHeadMapper;
import cn.iocoder.yudao.module.famous.doctor.dal.mysql.performance.ManagerOperatorPerformanceService;
import cn.iocoder.yudao.module.famous.doctor.dal.mysql.performance.PerformanceHeadMapper;
import cn.iocoder.yudao.module.famous.doctor.dal.mysql.performance.PerformancePublishItemService;
import cn.iocoder.yudao.module.famous.doctor.dal.mysql.performance.PerformancePublishMapper;
import cn.iocoder.yudao.module.famous.doctor.service.forimRecord.UserProjectItemService;
import cn.iocoder.yudao.module.famous.doctor.utils.JsonUtils;
import cn.iocoder.yudao.module.member.dal.dataobject.user.MemberUserDO;
import cn.iocoder.yudao.module.member.dal.mysql.user.MemberUserMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;

import dm.jdbc.util.StringUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.web.core.util.WebFrameworkUtils.getLoginUserId;
import static cn.iocoder.yudao.module.famous.doctor.enums.ErrorCodeConstants.FROM_INVALID;

/**
 * 后台-绩效管理
 *
 * @author wyx
 * @since 2021-08-17
 */
@Validated
@RestController
@RequestMapping("/manager/performance")
@Tag(name = "后台-绩效管理")
public class PerformanceHeadController {

	@PostMapping("/save")
	@Operation(summary="绩效管理 - 保存")
	public CommonResult<PerformanceHead> save(@RequestBody PerformanceHead performanceHead) {
		Long userId = getLoginUserId();
		MemberUserDO memberUserDO = memberUserMapper.selectById(userId);
		performanceHead.setModifiedUserId(userId);
		performanceHead.setModifiedUserName(memberUserDO.getNickname());
		if (performanceHead.getId() == null) {
			performanceHead.setKey(IdUtil.fastSimpleUUID());
			performanceHeadMapper.insert(performanceHead);
		}
		else {
			performanceHeadMapper.updateById(performanceHead);
		}
		return success(performanceHead);
	}

	@GetMapping("/list")
	@Operation(summary="绩效管理 - 列表")
	@Parameter(name = "pageNum", description = "当前页码", required = false, example = "1")
	@Parameter(name = "pageSize", description = "每页显示记录数", required = false, example = "1")
	@Parameter(name = "name", description = "业务名称", required = false, example = "1")
	public CommonResult<IPage<PerformanceHead>> list(@RequestParam(required = false) Map<String, Object> params) {
		String name = params.containsKey("name") ? params.get("name").toString().trim() : null;

		IPage<PerformanceHead> page = performanceHeadMapper.selectPage(new Query().getPage(params),new QueryWrapper<PerformanceHead>()
				.like(StringUtil.isNotEmpty(name), "name", name));
		return success(page);
	}

	@DeleteMapping("/delete")
	@Operation(summary="绩效管理 - 删除")
	public CommonResult delete(Long id) {
		performanceHeadMapper.deleteById(id);
		return success(id);
	}

	@GetMapping("/view")
	@Operation(summary="绩效管理 - 详情")
	public CommonResult<PerformanceHead> view(Long id) {
		PerformanceHead performanceHead = performanceHeadMapper.selectById(id);
		return success(performanceHead);
	}

	@PostMapping("/publish")
	@Operation(summary="绩效管理 - 发布")
	public CommonResult<PerformancePublish> publish(@RequestBody PerformancePublish performancePublish) {
		Long count = projectItemService
				.count(Wrappers.<UserProjectItemEntity>lambdaQuery().eq(UserProjectItemEntity::getProjectKey, performancePublish.getPkey()));
		if (count == 0) {
			throw exception(FROM_INVALID);
		}

		PerformanceHead performanceHead = performanceHeadMapper.selectById(performancePublish.getPid());
		performancePublish.setKey(IdUtil.fastSimpleUUID());
		performancePublish.setName(performanceHead.getName());
		performancePublish.setRemake(performanceHead.getRemake());
		performancePublishMapper.insert(performancePublish);

		List<UserProjectItemEntity> userProjectItemEntities = projectItemService.listByProjectKey(performanceHead.getKey());
		List<PerformancePublishItem> performancePublishItemList = JsonUtils.jsonToList(JsonUtils.objToJson(userProjectItemEntities), PerformancePublishItem.class);
		performancePublishItemList.forEach(item -> item.setProjectKey(performancePublish.getKey()));
		performancePublishItemService.saveBatch(performancePublishItemList);

		//给所有运营商添加消息
//		List<UserOperator> userOperators = userOperatorMapper.selectList(null);
//		for (UserOperator userOperator : userOperators) {
//			userMessageService.addPerformance(userOperator.getId(),"已添加" + performancePublish.getTitle() + "考核信息，请尽快填写");
//		}
		return success(performancePublish);
	}

	@PostMapping("/publishSave")
	@Operation(summary="绩效管理-发布 - 编辑")
	public CommonResult<PerformancePublish> publishSave(@RequestBody PerformancePublish performancePublish) {
		performancePublishMapper.updateById(performancePublish);
		return success(performancePublish);
	}

	@DeleteMapping("/publishDel")
	@Operation(summary="绩效管理 -发布-删除")
	public CommonResult publishDel(Long id) {
		performancePublishMapper.deleteById(id);
		return success(id);
	}

	@GetMapping("/publishList")
	@Operation(summary="绩效管理-发布 - 列表")
	@Parameter(name = "pageNum", description = "当前页码", required = false, example = "1")
	@Parameter(name = "pageSize", description = "每页显示记录数", required = false, example = "1")
	@Parameter(name = "pid", description = "主题id", required = false, example = "1")
	public CommonResult<IPage<PerformancePublish>> publishList(@RequestParam(required = false) Map<String, Object> params) {
		String pid = params.containsKey("pid") ? params.get("pid").toString().trim() : null;
//		String startTime = params.containsKey("startTime") ? params.get("startTime").toString().trim() : null;
//		String endTime = params.containsKey("endTime") ? params.get("endTime").toString().trim() : null;

		IPage<PerformancePublish> page = performancePublishMapper.selectPage(new Query().getPage(params), new QueryWrapper<PerformancePublish>()
				.eq(StringUtil.isNotEmpty(pid), "pid", pid)
		);
		return success(page);
	}

	@GetMapping("/listPerformancePublishItem")
	@Operation(summary="绩效发布-表单项")
	public CommonResult<List<PerformancePublishItem>> listPerformancePublishItem(String key) {
		List<PerformancePublishItem> list = performancePublishItemService.list(Wrappers.<PerformancePublishItem>lambdaQuery().eq(PerformancePublishItem::getProjectKey, key));
		return success(list);
	}

	@GetMapping("/listOperatorPerformance")
	@Operation(summary="绩效管理 - 运营商模板 - 列表")
	@Parameter(name = "pageNum", description = "当前页码", required = false, example = "1")
	@Parameter(name = "pageSize", description = "每页显示记录数", required = false, example = "1")
	@Parameter(name = "name", description = "业务名称", required = false, example = "1")
	public CommonResult<IPage<OperatorPerformanceHead>> listOperatorPerformance(@RequestParam(required = false) Map<String, Object> params) {
		String name = params.containsKey("name") ? params.get("name").toString().trim() : null;
		IPage<OperatorPerformanceHead> page = operatorPerformanceHeadMapper.selectPage(new Query().getPage(params),new QueryWrapper<OperatorPerformanceHead>().lambda()
						.like(StringUtil.isNotEmpty(name), OperatorPerformanceHead::getName, name)
						.eq(OperatorPerformanceHead::getIsTemplate,1)
		);
		return success(page);
	}

	@PostMapping("/saveOperatorPerformance")
	@Operation(summary="绩效管理 - 运营商模板 - 保存")
	public CommonResult<OperatorPerformanceHead> saveOperatorPerformance(@RequestBody OperatorPerformanceHead operatorPerformanceHead) {
		return success(managerOperatorPerformanceService.save(operatorPerformanceHead));
	}

	@GetMapping("/publishOperatorPerformance")
	@Operation(summary="绩效管理 - 运营商模板 - 发布")
	@Parameter(name = "id", description = "模板id", required = false, example = "1")
	@Parameter(name = "status", description = "0撤销发布 1发布", required = false, example = "1")
	public CommonResult publishOperatorPerformance(Long id,int status) {
		managerOperatorPerformanceService.publishOperatorPerformance(id,status);
		return success(0);
	}

	@DeleteMapping("/deleteOperatorPerformance")
	@Operation(summary="绩效管理 - 运营商模板 - 删除")
	public CommonResult deleteOperatorPerformance(Long id) {
		operatorPerformanceHeadMapper.deleteById(id);
		return success(id);
	}


	@Autowired
	private ManagerOperatorPerformanceService managerOperatorPerformanceService;
	@Autowired
	private OperatorPerformanceHeadMapper operatorPerformanceHeadMapper;
	@Autowired
	private PerformanceHeadMapper performanceHeadMapper;
	@Autowired
	private PerformancePublishMapper performancePublishMapper;
	@Autowired
	private PerformancePublishItemService performancePublishItemService;
	@Autowired
	private UserProjectItemService projectItemService;
	@Resource
	private MemberUserMapper memberUserMapper;
}
